#!/usr/bin/python
#coding=utf-8

import Cookie
import urlparse
import cgi
from igor import logging

class Request:
    """封装请求类。
    """

    def __init__(self, environ):
        self.method = environ['REQUEST_METHOD']
        #self.uri = environ['REQUEST_URI']
        self.query_string = environ['QUERY_STRING']
        self.path_info = environ['PATH_INFO']
        #self.server_protocol = environ['SERVER_PROTOCOL']
        self.server_name = environ['SERVER_NAME']
        self.server_port = environ['SERVER_PORT']
        self.cookie_string = environ.get('HTTP_COOKIE')
        self.args = {} 
        self.__set_args(environ)

    def __set_args(self, environ):
        if self.method == 'GET':
            if self.query_string:
                logging.log('get method, query_string=' + self.query_string)
                self.args = urlparse.parse_qs(self.query_string)
        elif self.method == 'POST':
            input_data = environ['wsgi.input']
            if input_data:
                self.args = cgi.parse(fp=input_data, environ=environ)
        else:
            raise Exception('not support method')

    def get_cookies(self):
        if not hasattr(self, 'cookies'):
            self.cookies = Cookie.SimpleCookie() 
            if self.cookie_string:
                self.cookies.load(self.cookie_string)
        return self.cookies



